package com.ruoyi.project.remake.service.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.AuthUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.remake.domain.*;
import com.ruoyi.project.remake.domain.constant.InitConstant;
import com.ruoyi.project.remake.domain.dto.BorrowApprovalDto;
import com.ruoyi.project.remake.domain.dto.CaseDetailDto;
import com.ruoyi.project.remake.domain.enmu.RemakeStatusState;
import com.ruoyi.project.remake.domain.enmu.YesORNoEnum;
import com.ruoyi.project.remake.domain.query.PrintDetailsQuery;
import com.ruoyi.project.remake.domain.query.ReportQuery;
import com.ruoyi.project.remake.domain.utils.ImageToPdfUtil;
import com.ruoyi.project.remake.domain.vo.*;
import com.ruoyi.project.remake.service.*;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.TDoctorClass;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysDictDataService;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.system.service.ITDoctorClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.remake.mapper.TRemakeCaseDetailsMapper;

/**
 * 翻拍病例详情Service业务层处理
 *
 * @author 孙山伟
 * @date 2020-12-15
 */
@Service
public class TRemakeCaseDetailsServiceImpl implements ITRemakeCaseDetailsService {
    @Autowired
    private TRemakeCaseDetailsMapper tRemakeCaseDetailsMapper;
    @Autowired
    private ITDoctorClassService doctorClassService;
    @Autowired
    private ITBorrowApprovalService borrowApprovalService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ITCaseMainService caseMainService;
    @Autowired
    private IPrintClassService printClassService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IApplyDocumentService applyDocumentService;
    /**
     * 查询翻拍病例详情
     *
     * @param id 翻拍病例详情ID
     * @return 翻拍病例详情
     */
    @Override
    public TRemakeCaseDetails selectTRemakeCaseDetailsById(Long id) {
        return tRemakeCaseDetailsMapper.selectTRemakeCaseDetailsById(id);
    }

    /**
     * 查询翻拍病例详情列表
     *
     * @param tRemakeCaseDetails 翻拍病例详情
     * @return 翻拍病例详情
     */
    @Override
    public List<TRemakeCaseDetails> selectTRemakeCaseDetailsList(TRemakeCaseDetails tRemakeCaseDetails) {
        return tRemakeCaseDetailsMapper.selectTRemakeCaseDetailsList(tRemakeCaseDetails);
    }

    /**
     * 新增翻拍病例详情
     *
     * @param tRemakeCaseDetails 翻拍病例详情
     * @return 结果
     */
    @Override
    public TRemakeCaseDetails insertTRemakeCaseDetails(TRemakeCaseDetails tRemakeCaseDetails) {
        tRemakeCaseDetails.setCreateTime(DateUtils.getNowDate());
        tRemakeCaseDetailsMapper.insertTRemakeCaseDetails(tRemakeCaseDetails);
        return tRemakeCaseDetails;
    }

    /**
     * 修改翻拍病例详情
     *
     * @param tRemakeCaseDetails 翻拍病例详情
     * @return 结果
     */
    @Override
    public int updateTRemakeCaseDetails(TRemakeCaseDetails tRemakeCaseDetails) {
        tRemakeCaseDetails.setUpdateTime(DateUtils.getNowDate());
        return tRemakeCaseDetailsMapper.updateTRemakeCaseDetails(tRemakeCaseDetails);
    }

    /**
     * 批量删除翻拍病例详情
     *
     * @param ids 需要删除的翻拍病例详情ID
     * @return 结果
     */
    @Override
    public int deleteTRemakeCaseDetailsByIds(Long[] ids) {
        return tRemakeCaseDetailsMapper.deleteTRemakeCaseDetailsByIds(ids);
    }

    /**
     * 删除翻拍病例详情信息
     *
     * @param id 翻拍病例详情ID
     * @return 结果
     */
    @Override
    public int deleteTRemakeCaseDetailsById(Long id) {
        return tRemakeCaseDetailsMapper.deleteTRemakeCaseDetailsById(id);
    }

    /**
     * 病例首页信息初始化回显
     *
     * @param id
     * @return
     */
    @Override
    public List<TRemakeCaseDetails> remakeDetails(Long id, String classType) {
        TRemakeCaseDetails tRemakeCaseDetails = new TRemakeCaseDetails();
        tRemakeCaseDetails.setClassType(classType);
        tRemakeCaseDetails.setCaseMainId(id);
        List<TRemakeCaseDetails> list = tRemakeCaseDetailsMapper.selectNewDetailsList(tRemakeCaseDetails);
        /*SysDictData dictData = new SysDictData();
        dictData.setDictType(Constants.CASE_CLASS);
        List<SysDictData> sysDictDataList= dictDataService.selectDictDataList(dictData);
        for( int i=0;i<list.size();i++){
            TRemakeCaseDetails tRemakeCaseDetails1=list.get(i);
            for(SysDictData sysDictData:sysDictDataList){
                if(sysDictData.getDictValue().equals(tRemakeCaseDetails1.getClassType())){
                    tRemakeCaseDetails1.setClassType(sysDictData.getDictLabel());
                }
            }
        }*/
        return list;
    }

    @Override
    public void deleteByClassType(Long id, String classType) {
        TRemakeCaseDetails tRemakeCaseDetails = new TRemakeCaseDetails();
        tRemakeCaseDetails.setClassType(classType);
        tRemakeCaseDetails.setCaseMainId(id);
        tRemakeCaseDetailsMapper.deleteByClassType(tRemakeCaseDetails);
    }

    @Override
    public void InterphoneImg(TRemakeCaseDetails tRemakeCaseDetails) {

        //修改其他图片的序号
        List<TRemakeCaseDetails> lists = tRemakeCaseDetailsMapper.selectNeedInter(tRemakeCaseDetails);
        for (TRemakeCaseDetails tRemakeCaseDetails1 : lists) {

            if (null == tRemakeCaseDetails1.getImgXh()) {
                tRemakeCaseDetails1.setImgXh(1);
            } else {
                tRemakeCaseDetails1.setImgXh(tRemakeCaseDetails1.getImgXh() + 1);
            }
            updateTRemakeCaseDetails(tRemakeCaseDetails1);
        }
        //保存该图片
        tRemakeCaseDetails.setCreateBy(tRemakeCaseDetails.getUserName());
        tRemakeCaseDetails.setImgPath(configService.selectConfigByKey(InitConstant.PRO_IMG_KEY) + "/" + tRemakeCaseDetails.getImgPath());
        String imgName = tRemakeCaseDetails.getImgName();
        String[] tmp = imgName.split("/");
        imgName = tmp[tmp.length - 1];
        tRemakeCaseDetails.setImgName(imgName);
        tRemakeCaseDetails.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
        tRemakeCaseDetails.setCreateBy(tRemakeCaseDetails.getUserName());
        insertTRemakeCaseDetails(tRemakeCaseDetails);
    }

    @Override
    public List<CaseFrontVo> selectByFront(CaseDetailDto caseDetailDto) {

        return null;
    }

    @Override
    public AjaxResult tRemakeCaseDetails(CaseDetailDto caseDetailDto) {
        //如果为医生则进行判定是否有权限
        if (caseDetailDto.getType().equals(InitConstant.DOCTOR_TYPE)) {
            Long doctorId = caseDetailDto.getUserId();
            TDoctorClass tDoctorClass = new TDoctorClass();
            tDoctorClass.setDoctorId(doctorId);
            List<TDoctorClass> tDoctorClassList = doctorClassService.selectTDoctorClassList(tDoctorClass);
            boolean isFlag = false;
            for (TDoctorClass entity : tDoctorClassList) {
                String classValue = entity.getClassValue();
                if (caseDetailDto.getClassType().equals(classValue)) {
                    isFlag = true;
                    break;
                }
            }
            if (!isFlag) {
                BorrowApprovalDto dto = new BorrowApprovalDto();
                dto.setApplyDoctor(doctorId);
                dto.setBorrowTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()));
                dto.setCaseMainId(caseDetailDto.getCaseMainId());
                dto.setClassType(caseDetailDto.getClassType());
                List<TBorrowApproval> borrowApprovalList = borrowApprovalService.selectFrontApprovalList(dto);
                if (null != borrowApprovalList && borrowApprovalList.size() != 0) {
                    isFlag = true;
                }

            }
            if (!isFlag) {//如果没有权限
                return AjaxResult.error(HttpStatus.UNAUTHORIZED, "您没有权限查看");
            }
        }
        //根据分类和ID查询病例详情
        TRemakeCaseDetails tRemakeCaseDetails = new TRemakeCaseDetails();
        tRemakeCaseDetails.setCaseMainId(caseDetailDto.getCaseMainId());
        tRemakeCaseDetails.setClassType(caseDetailDto.getClassType());
        List<TRemakeCaseDetails> tRemakeCaseDetailsList = tRemakeCaseDetailsMapper.selectTRemakeCaseDetailsList(tRemakeCaseDetails);
        for (TRemakeCaseDetails tRemakeCaseDetails1 : tRemakeCaseDetailsList) {
            // tRemakeCaseDetails1.setImgPath(configService.selectConfigByKey(InitConstant.PRO_IMG_KEY+tRemakeCaseDetails1.getImgName()));
        }
        //执行查询如果为超级管理员，则不执行去除操作
        SysUser sysUser = userService.selectUserById(caseDetailDto.getUserId());
        List<SysRole> sysRoleList = sysUser.getRoles();
        int flag = 0;
        for (SysRole sysRole : sysRoleList) {
            if (sysRole.getRoleKey().equals(InitConstant.ADMIN)) {
                flag = 1;
                break;
            }
        }

        if (flag == 0) {
            SysDictData dictData = new SysDictData();
            dictData.setDictType(Constants.CASE_CLASS);
            List<SysDictData> sysDictDataList = dictDataService.selectDictDataList(dictData);
            for (int i = 0; i < tRemakeCaseDetailsList.size(); i++) {
                TRemakeCaseDetails tRemakeCaseDetails1 = tRemakeCaseDetailsList.get(i);
                //tRemakeCaseDetails1.setImgPath(configService.selectConfigByKey(InitConstant.PRO_IMG_KEY)+tRemakeCaseDetails1.getImgName());
                for (SysDictData sysDictData : sysDictDataList) {
                    if (sysDictData.getDictValue().toString().equals(tRemakeCaseDetails1.getClassType())) {
                        if (sysDictData.getRemark().equals(InitConstant.IS_PRINT)) {//不允许打印
                            tRemakeCaseDetailsList.remove(i);
                            i--;
                            break;
                        }
                        tRemakeCaseDetails1.setClassType(sysDictData.getDictLabel());
                    }
                }
            }
        }
        return AjaxResult.success(tRemakeCaseDetailsList);
    }

    @Override
    public void toPDF(Long id) {
        TRemakeCaseDetails details = new TRemakeCaseDetails();
        details.setCaseMainId(id);
        List<TRemakeCaseDetails> remakeCaseDetailsList = selectTRemakeCaseDetailsList(details);
        List<String> imgList = remakeCaseDetailsList.stream().map(TRemakeCaseDetails::getImgPath).collect(Collectors.toList());
        String proKey = configService.selectConfigByKey(InitConstant.PRO_IMG_KEY);
        String repKey = RuoYiConfig.getProfile() + "/images/";
        for (int i = 0; i < imgList.size(); i++) {
            String imgs = imgList.get(i);

            String t2 = imgs.replaceAll(proKey, repKey);

            imgList.set(i, t2);
        }
        if (ObjectUtil.isNotEmpty(imgList) && imgList.size() != 0) {


            String path = imgList.get(0).replaceAll(".jpg", ".pdf");
            ImageToPdfUtil.toPdf(imgList, path);
            TCaseMain caseMain = new TCaseMain();
            caseMain.setPdfUrl(path.replaceAll(repKey, proKey));
            caseMain.setId(id);
            caseMainService.updateTCaseMain(caseMain);
        }
    }

    @Override
    public List<TRemakeCaseDetails> remakeDetails(Long id, Object o, String ids) {
        TRemakeCaseDetails tRemakeCaseDetails = new TRemakeCaseDetails();
        tRemakeCaseDetails.setClassType(null);
        tRemakeCaseDetails.setCaseMainId(id);
        tRemakeCaseDetails.setIds(ids.split(","));
        List<TRemakeCaseDetails> list = tRemakeCaseDetailsMapper.selectTRemakeCaseDetailsList(tRemakeCaseDetails);

        return list;

    }

    @Override
    public List<ReprotVo> selectReport(ReportQuery reportQuery) {
        return tRemakeCaseDetailsMapper.selectReport(reportQuery);
    }

    @Override
    public List<ReprotVo> selectReportDetails(ReportQuery reportQuery) {
        return tRemakeCaseDetailsMapper.selectReportDetails(reportQuery);
    }

    @Override
    public Integer getMaxXh(TRemakeCaseDetails tRemakeCaseDetails) {
        return tRemakeCaseDetailsMapper.selectMaxXh(tRemakeCaseDetails.getCaseMainId(), tRemakeCaseDetails.getClassType());
    }

    @Override
    public void saveBath(List<TRemakeCaseDetails> insertAll) {
        tRemakeCaseDetailsMapper.saveBath(insertAll);
    }

    @Override
    public List<PrintDetailsVo> selectCopyList(PrintDetailsQuery query) {
        //根据标签内容和类型返回该标签的值
        String dictValue=dictDataService.selectDictValue(InitConstant.PRINT_CLASS,query.getPringClassValue());
        //获取该打印分类下有哪些是可以进行打印的病例分类
        PrintClass printClass = new PrintClass();
        printClass.setStatus(YesORNoEnum.YES.getValue().toString());
        printClass.setPrintValue(dictValue);
        List<PrintClass> list = printClassService.selectPrintClassList(printClass);
        List<PrintDetailsVo> printDetailsVoList = tRemakeCaseDetailsMapper.selectCopyList(query);
        //对打印列表前的复选框进行勾选
        addIsCheck(list, printDetailsVoList);
        TRemakeCaseDetails details = new TRemakeCaseDetails();
        details.setCaseMainId(query.getCaseMainId());
        List<TRemakeCaseDetails> remakeCaseDetails = tRemakeCaseDetailsMapper.selectTRemakeCaseDetailsList(details);
        //整合分类打印下的打印详情列表
        addPrintDetails(remakeCaseDetails, printDetailsVoList);
        return printDetailsVoList;
    }

    /**
     * 打印模块的收费清单详情
     * @param caseMainId
     * @return
     */
    @Override
    public RemarkPrintDetailsVo loadIndexModel(Long caseMainId,List<PrintDetailsVo>  printDetailsVoList) {
        RemarkPrintDetailsVo vo=new RemarkPrintDetailsVo();
        CaseMainVo caseMain=caseMainService.selectTCaseMainById(caseMainId);
        //采集状态赋值
        if(ObjectUtil.isNull(caseMain)){
            vo.setGatherStatus(YesORNoEnum.YES.getMyDesp());
            //未归档
            vo.setStatus(InitConstant.DOCTOR_STATUS_ERROR);
            //归档时间置为--
            vo.setPlaceTime("--");
        }else{
            vo.setPatientsName(caseMain.getPatientsName());
            //采集状态为已采集
            vo.setGatherStatus(YesORNoEnum.NO.getMyDesp());
            //如果审核状态为空，则认为为归档
           if(ObjectUtil.isNull(caseMain.getStatus())){
               vo.setStatus(InitConstant.DOCTOR_STATUS_ERROR);
               //归档时间置为--
               vo.setPlaceTime("--");
           }//如果为审核通过
           else if(RemakeStatusState.PASS_AUDIT.getValue().toString().equals(caseMain.getStatus())){
               vo.setStatus(InitConstant.DOCTOR_STATUS_SUCCESS);
               //归档时间为质检通过时间
               vo.setPlaceTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,caseMain.getQualityTime()));
           }else{//其他情况则置未归档
               vo.setStatus(InitConstant.DOCTOR_STATUS_ERROR);
               //归档时间置为--
               vo.setPlaceTime("--");
           }
        }

       //设定打印模式
        vo.setPrintModel(sysConfigService.selectConfigByKey(InitConstant.PRINT_MODEL));
        //打印单价
        vo.setUnitPrice(sysConfigService.selectConfigByKey(InitConstant.ONLY_PRICE));
        //计算打印张数
        Long pageNumber=getPageNumber(printDetailsVoList);
        vo.setTotalPage(pageNumber);
        vo.setTotalMonney(countMoney(vo.getUnitPrice(),pageNumber));
        return vo;
    }

    /**
     * 根据申请id整理成PDF文件
     * @param applyId
     * @return
     */
    @Override
    public String printPDF(Long applyId) {
        ApplyDocument applyDocument=applyDocumentService.selectApplyDocumentById(applyId);
        //根据标签内容和类型返回该标签的值
        String dictValue=dictDataService.selectDictValue(InitConstant.PRINT_CLASS,applyDocument.getCopyCause());
        //获取该打印分类下有哪些是可以进行打印的病例分类
        PrintClass printClass = new PrintClass();
        printClass.setStatus(YesORNoEnum.YES.getValue().toString());
        printClass.setPrintValue(dictValue);
        List<PrintClass> list = printClassService.selectPrintClassList(printClass);
        PrintDetailsQuery query=new PrintDetailsQuery();
        query.setCaseMainId(applyDocument.getCaseMainId());
        query.setPringClassValue(applyDocument.getCopyCause());
        List<PrintDetailsVo> printDetailsVoList = tRemakeCaseDetailsMapper.selectCopyList(query);
        //对打印列表前的复选框进行勾选
        addIsCheck(list, printDetailsVoList);
        TRemakeCaseDetails details = new TRemakeCaseDetails();
        details.setCaseMainId(query.getCaseMainId());
        List<TRemakeCaseDetails> remakeCaseDetails = tRemakeCaseDetailsMapper.selectTRemakeCaseDetailsList(details);
        //整合分类打印下的打印详情列表
        addPrintDetails(remakeCaseDetails, printDetailsVoList);
        List<String> imgList=new ArrayList<>();
        for(PrintDetailsVo vo:printDetailsVoList){
            List<TRemakeCaseDetails> detailsList=vo.getRemakeCaseDetails();
            if(vo.getIsCheck()){
                List<String> collect = detailsList.stream().map(TRemakeCaseDetails::getImgPath).collect(Collectors.toList());
                imgList.addAll(collect);
            }
        }
        String urlPath=RuoYiConfig.getProfile()+InitConstant.PDF_URL+applyDocument.getCaseMainId()+"/"+applyDocument.getCopyCause()+".pdf";
        File file=new File(urlPath);
        File pafile=file.getParentFile();
        //不存在父路径就创建
        if(!pafile.exists())
        {
            pafile.mkdirs();
        }
       if(!file.exists()){
           try {
               file.createNewFile();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }

        ImageToPdfUtil.toPdf(imgList,urlPath);
        String proKey = configService.selectConfigByKey(InitConstant.PRO_IMG_KEY);
        String result=proKey+"/"+applyDocument.getCaseMainId()+"/"+applyDocument.getCopyCause()+".pdf";
        return result;
    }

    /**
     * 计算总价格
     * @param unitPrice  单价
     * @param pageNumber  页码总数
     * @return
     */
    private BigDecimal countMoney(String unitPrice, Long pageNumber) {
        BigDecimal bigDecimal=new BigDecimal(unitPrice);
        BigDecimal number=new BigDecimal(pageNumber);
        BigDecimal result=bigDecimal.multiply(number).setScale(BigDecimal.ROUND_CEILING);
        return  result;
    }

    private Long getPageNumber(List<PrintDetailsVo> printDetailsVoList) {
        Long sum=0L;
        for(PrintDetailsVo vo:printDetailsVoList){
            if(vo.getIsCheck()){
                sum+=vo.getPrintNumber();
            }
        }
        return sum;
    }

    /**
     * 整合分类打印下的打印详情列表
     *
     * @param remakeCaseDetails
     * @param printDetailsVoList
     */
    private void addPrintDetails(List<TRemakeCaseDetails> remakeCaseDetails, List<PrintDetailsVo> printDetailsVoList) {
        for (PrintDetailsVo vo : printDetailsVoList) {
            List<TRemakeCaseDetails> details = new ArrayList<>();
            for (TRemakeCaseDetails caseDetails : remakeCaseDetails) {
                if (vo.getClassType().equals(caseDetails.getClassType())) {
                    details.add(caseDetails);
                }
            }
            vo.setRemakeCaseDetails(details);
        }

    }

    /**
     * 对打印列表前的内容进行整合，是否选中进行打钩
     *
     * @param list
     * @param printDetailsVoList
     */
    private void addIsCheck(List<PrintClass> list, List<PrintDetailsVo> printDetailsVoList) {
        for (PrintClass printClass : list) {
            for (PrintDetailsVo printDetailsVo : printDetailsVoList) {
                if (printClass.getClassValue().equals(printDetailsVo.getClassType())) {
                    printDetailsVo.setIsCheck(true);
                    break;
                }
            }
        }
        for (PrintDetailsVo printDetailsVo : printDetailsVoList) {
            if (ObjectUtil.isNull(printDetailsVo.getIsCheck())) {
                printDetailsVo.setIsCheck(false);
            } else if (!printDetailsVo.getIsCheck()) {
                printDetailsVo.setIsCheck(false);
            }
        }
    }

}
